package com.dangfei.servlet;

import com.dangfei.dao.WorksDao;
import com.dangfei.daoimp.WorkslDaoImp;
import com.dangfei.model.Works;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Servlet implementation class Register
 */
@WebServlet("/Adddetail")
public class Adddetail extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Adddetail() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("title");
        String desc = request.getParameter("desc");
        String price = request.getParameter("price");
        String classid = request.getParameter("classid");
        //设置编码输出格式
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        String res = "{\"code\":201,\"msg\":\"参数缺失\"}";
        //判断用户名和密码是否均不为空
        if ((name == null) || (desc == null) || (price == null) || (classid == null)) {
        } else {
            if ((name.equals("")) || (desc.equals("")) || (price.equals("")) || (classid.equals(""))) {
                
            } else {
                Works work = new Works();
                work.setTitle(name);
                work.setContent(desc);
                work.setPrice(Double.parseDouble(price));
                work.setToclassid(Integer.parseInt(classid));
                WorksDao wd = new WorkslDaoImp();
                work = wd.CreateWork(work);
                boolean reg = wd.InsertToDB(work);
                //判断登陆结果
                if (reg) {
                    res = "{\"code\":200,\"msg\":\"新增成功!\"}";
                } else {
                    res = "{\"code\":202,\"msg\":\"新增失败！\"}";
                }
            }
        }
        out.println(res);
    }

}
